<?php
/**
 * 模拟getFile.php的上传测试
 */

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/oss_config.php';

use AlibabaCloud\Oss\V2 as Oss;

// 模拟getOssConfig函数
function getOssConfig() {
    $configFile = __DIR__ . '/oss_config.php';
    if (file_exists($configFile)) {
        $config = include $configFile;
        if (isset($config['access_key_id']) && isset($config['access_key_secret'])) {
            return $config;
        }
    }
    return null;
}

try {
    echo "=== 模拟getFile.php上传测试 ===\n";

    $ossConfig = getOssConfig();
    if (!$ossConfig) {
        die("无法获取OSS配置\n");
    }

    echo "配置信息:\n";
    echo "Access Key ID: " . substr($ossConfig['access_key_id'], 0, 8) . "...\n";
    echo "Region: " . $ossConfig['region'] . "\n";
    echo "Bucket: " . $ossConfig['bucket_name'] . "\n";
    echo "Endpoint: " . $ossConfig['endpoint'] . "\n\n";

    // 创建凭证提供者
    $credentialsProvider = new Oss\Credentials\StaticCredentialsProvider(
        $ossConfig['access_key_id'],
        $ossConfig['access_key_secret']
    );

    // 创建配置
    $cfg = new Oss\Config();
    $cfg->setCredentialsProvider($credentialsProvider);
    $cfg->setRegion($ossConfig['region']);
    $cfg->setEndpoint($ossConfig['endpoint']);
    $cfg->setConnectTimeout(30);

    // 创建客户端
    $client = new Oss\Client($cfg);

    // 模拟微信图片数据
    $testImageData = file_get_contents('https://opencdn.ydsjt.cn/image/20251018/1760782635720_476071.jpg');
    if (!$testImageData) {
        // 如果无法获取测试图片，创建一个简单的测试数据
        $testImageData = "测试图片数据 - " . date('Y-m-d H:i:s');
    }

    // 生成文件名（模拟getFile.php的逻辑）
    $filename = "uploads/wx/" . date('YmdHis') . rand(1000, 9999) . ".jpg";

    echo "正在上传测试文件...\n";
    echo "文件名: " . $filename . "\n";
    echo "文件大小: " . strlen($testImageData) . " bytes\n\n";

    // 创建上传请求
    $request = new Oss\Models\PutObjectRequest($ossConfig['bucket_name'], $filename);
    $request->body = Oss\Utils::streamFor($testImageData);
//    $request->setContentType('image/jpeg');

    // 执行上传
    $result = $client->putObject($request);

    echo "上传结果:\n";
    echo "状态码: " . $result->statusCode . "\n";

    if ($result->statusCode == 200) {
        $url = "http://{$ossConfig['bucket_name']}.oss-{$ossConfig['region']}.aliyuncs.com/".$filename;
        echo "✅ 上传成功！\n";
        echo "文件URL: " . $url . "\n";

        // 测试文件是否可以访问
        $headers = get_headers($url);
        if ($headers && strpos($headers[0], '200') !== false) {
            echo "✅ 文件可以正常访问\n";
        } else {
            echo "⚠️ 文件可能无法访问\n";
        }
    } else {
        echo "❌ 上传失败\n";
    }

} catch (Exception $e) {
    echo "❌ 上传测试失败！\n";
    echo "错误信息: " . $e->getMessage() . "\n";
    echo "错误代码: " . $e->getCode() . "\n";
    echo "错误类型: " . get_class($e) . "\n";
}
?>
